import React, { useState, useEffect, useRef } from 'react';
import { v4 as uuidv4 } from 'uuid';
import './Chat.css';

const Chat = () => {
    const [messages, setMessages] = useState([]); // 存储消息
    const [input, setInput] = useState(''); // 输入框内容
    const [userId] = useState(uuidv4()); // 当前用户 ID
    const [targetUserId, setTargetUserId] = useState(''); // 目标用户 ID
    const [availableUsers, setAvailableUsers] = useState([]); // 在线用户列表
    const ws = useRef(null); // WebSocket 引用

    // 初始化 WebSocket
    useEffect(() => {
        ws.current = new WebSocket('ws://localhost:8080');

        ws.current.onopen = () => {
            console.log('Connected to WebSocket server');
            // 发送用户注册消息
            ws.current.send(JSON.stringify({ type: 'register', userId }));
        };

        ws.current.onmessage = (event) => {
            const data = JSON.parse(event.data);
            if (data.type === 'userList') {
                // 更新在线用户列表
                setAvailableUsers(data.users.filter((id) => id !== userId));
            } else if (data.type === 'message') {
                // 接收私聊消息
                setMessages((prev) => [...prev, data.message]);
            }
        };

        ws.current.onclose = () => {
            console.log('Disconnected from WebSocket server');
        };

        ws.current.onerror = (error) => {
            console.error('WebSocket error:', error);
        };

        return () => {
            ws.current.close();
        };
    }, [userId]);

    // 发送消息
    const handleSendMessage = () => {
        if (input.trim() && targetUserId && ws.current.readyState === WebSocket.OPEN) {
            const message = {
                type: 'message',
                message: {
                    text: input,
                    sender: userId,
                    receiver: targetUserId,
                    id: uuidv4(), // 使用 uuid 生成唯一 ID
                },
            };
            ws.current.send(JSON.stringify(message));
            setMessages((prev) => [...prev, message.message]); // 本地显示发送的消息
            setInput(''); // 清空输入框
        }
    };

    // 支持回车发送
    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            handleSendMessage();
        }
    };

    return (
        <div className="chat-container">
            <div className="user-selection">
                <label>选择聊天对象：</label>
                <select
                    value={targetUserId}
                    onChange={(e) => setTargetUserId(e.target.value)}
                >
                    <option value="">-- 选择用户 --</option>
                    {availableUsers.map((id) => (
                        <option key={id} value={id}>
                            用户 {id.slice(0, 8)}
                        </option>
                    ))}
                    <option value="bot">机器人</option>
                </select>
                <p>您的用户 ID: {userId.slice(0, 8)}</p>
            </div>
            <div className="messages">
                {messages
                    .filter(
                        (msg) =>
                            (msg.sender === userId && msg.receiver === targetUserId) ||
                            (msg.sender === targetUserId && msg.receiver === userId)
                    )
                    .map((msg) => (
                        <div
                            key={msg.id}
                            className={`message ${msg.sender === userId ? 'user' : 'bot'}`}
                        >
                            {msg.text}
                        </div>
                    ))}
            </div>
            <div className="input-area">
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyPress={handleKeyPress}
                    placeholder="输入消息..."
                    disabled={!targetUserId}
                />
                <button onClick={handleSendMessage} disabled={!targetUserId}>
                    发送
                </button>
            </div>
        </div>
    );
};

export default Chat;